// ProgressDlg.cpp : implementation file
//

#include "stdafx.h"
#include "GPEncrypt.h"
#include "ProgressDlg.h"

#include "ExchangeData.h"

#include "GPEncryptDlg.h"

// CProgressDlg dialog

IMPLEMENT_DYNAMIC(CProgressDlg, CDialog)

CProgressDlg::CProgressDlg(CString title, CWnd* pParent /*=NULL*/)
	: CDialog(CProgressDlg::IDD, pParent)
{
	this->title = title;
	this->pParent = pParent;
	this->user_cancel = false;
}

CProgressDlg::~CProgressDlg()
{
}

void CProgressDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_PROGRESS_PROCESS, m_progress_process);
}

BOOL CProgressDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	//Prepare progress
	this->m_progress_process.SetRange(0,100);
	this->m_progress_process.SetPos(0);

	//Prepare title
	this->SetWindowText(this->title);

	//Set timer
	SetTimer(0,100,NULL);

	return TRUE;
}

BEGIN_MESSAGE_MAP(CProgressDlg, CDialog)
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTON_CANCEL, &CProgressDlg::OnBnClickedButtonCancel)
	ON_WM_TIMER()
	ON_WM_DESTROY()
	ON_WM_CLOSE()
END_MESSAGE_MAP()

BOOL CProgressDlg::PreTranslateMessage(MSG* pMsg)
{
	if(pMsg->message == WM_KEYDOWN) 
	{
		switch(pMsg->wParam) 
		{
		case VK_ESCAPE: //ESC
			return TRUE;
		}
	}
	return CDialog::PreTranslateMessage(pMsg);
}

// CProgressDlg message handlers
void CProgressDlg::OnBnClickedButtonCancel()
{
	// TODO: Add your control notification handler code here
	if (this->pParent != NULL)
	{
		CGPEncryptDlg* dlg = (CGPEncryptDlg*)this->pParent;
		OutputDebugString("Send WM_USER_PROGRESS_DLG_CANCEL\n");
		dlg->SendMessage(WM_USER_PROGRESS_DLG_CANCEL);
	}

	this->user_cancel = true;
	this->SendMessage(WM_CLOSE);
}

void CProgressDlg::OnTimer(UINT_PTR uid)
{
	int pos = 0;
	CString stringTmp;

	pos = *pexdata_percent_value;

	if (pos >= 99)
	{
		this->SendMessage(WM_CLOSE);
	}
	else
	{
		m_progress_process.SetPos(pos);

		stringTmp.Format("%s %3d%%",this->title.GetBuffer(), pos);
		this->SetWindowText(stringTmp);
	}
}

void CProgressDlg::OnDestroy()
{
	KillTimer(0);
}

void CProgressDlg::OnClose()
{
	//If finish close.
	//else if user click close button, do nothing.
	if ((*pexdata_percent_value > 90) || (this->user_cancel))
	{
		CDialog::OnClose();
	}
}

